package com.hk.Mgr.web.controller.common;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.hk.commons.*;
import com.hk.commons.utils.MsgTypeConstants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.ReservationPhoneReq;
import com.hk.Mgr.web.message.order.ReservationPhoneRes;
import com.hk.Mgr.web.message.order.ReservationRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.enm.ReservationPayStatusEnum;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.order.Reservation;
import com.hk.commons.entity.product.Company;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.service.IFundInfo_Yimi;
import com.hk.service.IPush;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IReservation;
import com.hk.service.product.ICompany;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ISysUser;

@Controller
@RequestMapping(value = BaseCtrl.CommonRootPath + "/reservation")
public class ComReservationCtrl {

	private Logger logger = LoggerFactory.getLogger(ComReservationCtrl.class);

	@Autowired
	private IReservation reservationImpl;

	@Autowired
	private ISysUser userImpl;

	@Autowired
	private ICompany companyImpl;

	@Autowired
	private IProductInfo productInfoImpl;

	@Autowired
	private IFundInfo_Yimi fundInfoService;

	@Autowired
	private IOrderInfo orderInfoImpl;

	@Autowired
	private IPush pushService;

	@ResponseBody
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ResponseBase<Boolean> save(@RequestBody ReservationPhoneReq req) {

		//Long userId = CheckUserId.checkId(req.getUserId());
		Long userId = Long.valueOf(req.getUserId())   ;
		String productId = req.getProductId();
		String amount = req.getAmount();

		logger.info("/reservation/save" + " userId = " + userId
				+ "  product = " + productId + " amount = " + amount);
		ResponseBase<Boolean> resp = new ResponseBase<>();
		Long resultCode = null;
		String msg = "";
		// 如果任何一个参数为空，则返回错误
		if (!userImpl.existById(userId)) {
			msg = "用户传入参数错误";
			logger.error(msg);
			resp.setResult(false);
			resp.setMsg(msg);
			resp.setResultCode(StatusCode.EXCEPTION.key());
			return resp;
		} else {
			SysUser user = userImpl.findById(userId);

			Long productIdLong = Long.valueOf(productId);

			BigDecimal amountBigDecimal = new BigDecimal(amount);
			Reservation rv = new Reservation();

			// 添加用户信息
			rv.setUserId(userId);
			// 添加操作人信息
			rv.setOperator(userId);

			// 添加理财师信息
			if (StringHelper.isNotEmpty(user.getRecommendCode())) {
				SysUser financialPlanner = userImpl.getByPhoneNum(user
						.getRecommendCode());
				if (financialPlanner != null) {
					rv.setInside(financialPlanner.getId());
				}
			}

			// 添加预约产品信息
			ProductInfo product = productInfoImpl.findById(productIdLong);
			rv.setProductId(productIdLong);
			if (product != null) {
				rv.setCompanyId(product.getIssuerId());
			}
			// 设置预约状态为未付款
			rv.setStatus(Integer
					.valueOf(ReservationPayStatusEnum.RESERVATIONSTATUS_0
							.getCode()));
			// 添加预约金额
			rv.setAmount(amountBigDecimal);
			resultCode = reservationImpl.add(rv);

			if (resultCode != null) {
				
				try {
					ScheduledExecutorService executor = Executors
						.newScheduledThreadPool(1);
					Runnable task = () -> {
					// 更改产品的预约金额					
						sendPushToFinancial(user.getName(), user.getRealName(),
								StringHelper.myformat.format(amountBigDecimal),
								product.getName(), user.getRecommendCode());

						String message = String.format("您已成功预约一笔%s元的%s，请到预约记录中查看", StringHelper.myformat.format(amountBigDecimal), product.getName());
						this.pushService.jgPushCustomerMsg(message, "预约成功", null, null, null, user.getName(), ConstantPush.PUSH_MENU, MsgTypeConstants.APPOINTMENT);
					};
					executor.execute(task);
				} catch (Exception e) {
					logger.error("客户预约推送理财师异常！",e);
				}
				productInfoImpl.addBespeakAccount(productIdLong,
						amountBigDecimal);

				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());
			} else {
				msg = "ERROR: 保存客户订单信息错误!userId = " + userId;
				logger.error(msg);
				resp.setResult(false);
				resp.setMsg(msg);
				resp.setResultCode(StatusCode.EXCEPTION.key());
			}
		}
		return resp;
	}

    private void sendPushToFinancial(String custPhone, String custName,
                                     String amt, String productName, String phone) {
        if (StringUtils.isBlank(phone))
            return;

        // e.g. 您的客户张三 ，已成功预约1笔 50000元的盛世四海
        StringBuilder msg = new StringBuilder();
        msg.append(ConstantPush.PUSH_APPOINT_START);

        if(StringUtils.isNotBlank(custName))
            msg.append(custName);
        else
            msg.append(custPhone);

        msg.append(ConstantPush.PUSH_APPOINT_MIDDLE);
        msg.append(amt);
        msg.append(ConstantPush.PUSH_APPOINT_END);
        msg.append(productName);

        pushService.jgPushMsg(msg.toString(), null, null, null, phone,
                ConstantPush.PUSH_MENU_APPOINTMENT, MsgTypeConstants.APPOINTMENT);
    }

	@ResponseBody
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ResponseBase<List<ReservationPhoneRes>> list(
			@RequestBody ReservationPhoneReq req) {
		//Long userId = CheckUserId.checkId(req.getUserId());
		Long userId = Long.valueOf(req.getUserId());


		String curPage = req.getCurPage();
		String pageSize = req.getPageSize();

		logger.info("/reservation/list" + " userId = " + userId.toString()
				+ "  curPage = " + curPage + "pageSize " + pageSize);

		ResponseBase<List<ReservationPhoneRes>> resp = new ResponseBase<>();

		//限制销户用户-2.7.6
		SysUser user = userImpl.findById(userId);
		if(user == null || user.getCloseAccount() ==1){
			resp.setResult(null);
			resp.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
			resp.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
			return resp;
		}

		Integer curPageInt = null;
		if (StringUtils.isNotEmpty(curPage)) {
			curPageInt = Integer.valueOf(curPage);
		} else {
			curPageInt = 1;
		}

		Integer pageSizeInt = null;

		if (StringUtils.isNotEmpty(pageSize)) {
			pageSizeInt = Integer.valueOf(pageSize);
		} else {
			pageSizeInt = 10;
		}

		HqlFilter hqlFilter = new HqlFilter();

		/** 要传入userId */
		hqlFilter.addEQFilter("userId", userId);

		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");

		List<Reservation> list = reservationImpl.findByFilter(hqlFilter,
				curPageInt, pageSizeInt);

		// 返回集
		List<ReservationPhoneRes> rList = new ArrayList<>();

		if (list.size() != 0) {
			for (Reservation rt : list) {
				ReservationPhoneRes rr = new ReservationPhoneRes();

				// 预约订单id
				rr.setId(rt.getId().toString());
				rr.setProductId(rt.getProductId());
				ProductInfo productInfo = productInfoImpl.findById(rt
						.getProductId());
				if (productInfo != null) {
					if (productInfo.getIssuerId() != null) {
						Company company = companyImpl.findById(productInfo
								.getIssuerId());
						// 添加预约产品公司信息
						rr.setCompanyName(company.getName());
					}

					// 添加预约产品的名称
					rr.setProductName(productInfo.getName());

					// 添加预约产品的类型
					Integer type = productInfo.getProdType();

					rr.setProductType(getProdType(type));
				}

				// 设置预约的时间
				Timestamp createTime = new Timestamp(rt.getCts());
				rr.setCts(createTime.toString());

				// 设置预约的金额
				rr.setAmount(rt.getAmount().toString());

				// 设置预约的状态
				if (rt.getStatus() == 1) {
					rr.setReservationStatus("未打款");
				} else if (rt.getStatus() == 2) {
					rr.setReservationStatus("已打款");
				}

				rList.add(rr);
			}
		}
		resp.setResult(rList);
		resp.setSize(list.size());
		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/setInside")
	public ResponseBase<Boolean> setInside(@RequestBody ReservationRes res) {
		ResponseBase<Boolean> rb = new ResponseBase<>();
		Reservation rs = reservationImpl.findById(res.getId());
		// 分配的理财师ID
		rs.setInside(res.getOperator());
		// 记录操作人ID
		rs.setOperator(res.getOperator());
		rs.setUpts(System.currentTimeMillis());
		reservationImpl.update(rs);
		rb.setResult(true);
		return rb;
	}

	/**
	 * 根据预约信息生成订单
	 * 
	 * @param rs
	 *            产品预约信息
	 * @return True/False
	 */
	public boolean createOrder(Reservation rs) {
		boolean t = false;
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setProductId(rs.getProductId());
		orderInfo.setBrokerOrderNo(String.valueOf(rs.getId()));
		// 理财师ID
		orderInfo.setFinancialPlannerId(rs.getInside());

		orderInfoImpl.add(orderInfo);
		return t;

	}

	private String getProdType(Integer type) {
		String prodType = null;

		// 股票、债券、股权、债权、房地产、衍生品、文化传媒、其他
		if (type == 1) {
			prodType = "股票";
		} else if (type == 2) {
			prodType = "债券";
		} else if (type == 3) {
			prodType = "股权";
		} else if (type == 4) {
			prodType = "债权";
		} else if (type == 5) {
			prodType = "房地产";
		} else if (type == 6) {
			prodType = "衍生品";
		} else if (type == 7) {
			prodType = "文化传媒";
		} else if (type == 8) {
			prodType = "其它";
		}
		return prodType;
	}

}
